package com.bt.lms.ui.action.school_education.archives.register;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.RegisterInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.vo.school_education.registerInfo.EditRegisterInfoVo;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;
import java.time.ZoneOffset;

/**
 * 编辑注册信息验证事件
 */
public class EditRegisterVerify implements EventHandler {
    private VBox vBox;
    public EditRegisterVerify(VBox register) {
        this.vBox = register;
    }

    @Override
    public void handle(Event event) {
        //1.获取用户输入
        EditRegisterInfoVo editRegisterInfoVo = getInput();

        //2.验证输入
        String verifyMsg = getVerifyInput(editRegisterInfoVo);

        byte[] bytes = null;
        //3.组包
        if (null == verifyMsg) {
            bytes = handle2Msg(editRegisterInfoVo);
        } else {
            return;
        }
        //组网
        Socket socket = getNet();
        //发送消息
        boolean flag = sengMsg(socket, bytes,editRegisterInfoVo);

    }

    /**
     * 发送消息
     *
     * @param socket             网
     * @param bytes              要发送的字节数组
     * @param editRegisterInfoVo
     * @return 是否成功
     */
    private boolean sengMsg(Socket socket, byte[] bytes, EditRegisterInfoVo editRegisterInfoVo) {
        OutputStream out = null;
        try {
            out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //读取响应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);

            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            if (data != null){
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText("保存成功");
                alert.showAndWait();
            }
            //界面回显



            //关闭资源
            out.close();
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 获取网络
     *
     * @return 网
     */
    private Socket getNet() {
        Socket socket = null;

        try {
            socket = new Socket("127.0.0.1", 8888);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return socket;
    }

    /**
     * 组包
     *
     * @param editRegisterInfoVo vo对象
     * @return byte字节数组
     */
    private byte[] handle2Msg(EditRegisterInfoVo editRegisterInfoVo) {
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(StuStatusBizTypeConstant.REGISTER_INFO_BIZ_TYPE_EDIT);
        RegisterInfo registerInfo = new RegisterInfo();
        try {
            BeanUtils.copyProperties(registerInfo, editRegisterInfoVo);
            registerInfo.setId(1L);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        String registerStr = JSON.toJSONString(registerInfo);
        reqMsg.setData(registerStr);
        byte[] bytes = reqMsg.toBytes();

        return bytes;

    }

    /**
     * 验证用户输入
     *
     * @param editRegisterInfoVo vo对象
     * @return 验证后的str
     */
    private String getVerifyInput(EditRegisterInfoVo editRegisterInfoVo) {
        String msg = "";


        if (editRegisterInfoVo.getState() != null) {
        }

        long now = -1;
        if (editRegisterInfoVo.getDate() != null) {
            long data = editRegisterInfoVo.getDate().atStartOfDay()
                    .toInstant(ZoneOffset.of("+8")).toEpochMilli();
            now = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            if (data > now) {
                msg += "注册日期在当前时间之前\r\n";
            }
        }

        if (editRegisterInfoVo.getGotoDate() != null) {
            long data = editRegisterInfoVo.getGotoDate().atStartOfDay()
                    .toInstant(ZoneOffset.of("+8")).toEpochMilli();
            if (data > now) {
                msg += "报到日期在当前时间之前\r\n";
            }
        }

        String notRegisterCause = editRegisterInfoVo.getNotRegisterCause();
        if (notRegisterCause != null) {
            if (notRegisterCause.length() > 24) {
                msg += "未报到原因在0-24位之间之前\r\n";
            }
        }

        String notRegisterGo = editRegisterInfoVo.getNotRegisterGo();
        if (notRegisterGo != null) {
            if (notRegisterGo.length() > 32) {
                msg += "未注册/报到去向在0-32位之间之前\r\n";
            }
        }

        if (editRegisterInfoVo.getIsVacate() != null){

        }

        String schoolYear = editRegisterInfoVo.getSchoolYear();
        if (schoolYear != null) {
            if (schoolYear.length() > 24) {
                msg += "学年度在0-24位之间之前\r\n";
            }
        }

        String semester = editRegisterInfoVo.getSemester();
        if (semester != null) {
            if (semester.length() > 24) {
                msg += "学期在0-24位之间之前\r\n";
            }
        }

        String clas = editRegisterInfoVo.getClassroom();
        if (clas != null) {
            if (clas.length() > 24) {
                msg += "班级名称在0-24位之间之前\r\n";
            }
        }

        if (!msg.equals("")){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();
        }
        if (msg.equals("")){
            msg = null;
        }

        return msg;

    }

    /**
     * 获取用户输入
     *
     * @return vo对象
     */
    private EditRegisterInfoVo getInput() {
        EditRegisterInfoVo editRegisterInfoVo = new EditRegisterInfoVo();

        ComboBox conditionCB = (ComboBox) this.vBox.lookup("#conditionCB");

        if (conditionCB.getValue() != null) {
            int leave = -1;
            String conditionCBValue = (String) conditionCB.getValue();
            switch (conditionCBValue) {
                case "注册":
                    leave = BOConstant.REGISTER_INFO_STATE_REGISTER;
                    break;
                case "未注册":
                    leave = BOConstant.REGISTER_INFO_STATE_UNREGISTERED;
                    break;
                case "未报到":
                    leave = BOConstant.REGISTER_INFO_STATE_NO_SHOW;
                    break;
            }
            editRegisterInfoVo.setState(leave);
        }

        DatePicker registerTimeDP = (DatePicker) this.vBox.lookup("#registerTimeDP");
        LocalDate registerTimeDPValue = registerTimeDP.getValue();
        editRegisterInfoVo.setDate(registerTimeDPValue);

        DatePicker checkInTimeDP = (DatePicker) this.vBox.lookup("#checkInTimeDP");
        LocalDate checkInTimeDPValue = checkInTimeDP.getValue();
        editRegisterInfoVo.setGotoDate(checkInTimeDPValue);

        TextField notRegisterCauseTF = (TextField) this.vBox.lookup("#notRegisterCauseTF");
        String notRegisterCauseTFStr = notRegisterCauseTF.getText().trim();
        editRegisterInfoVo.setNotRegisterCause(notRegisterCauseTFStr);

        TextField notRegisterGoTF = (TextField) this.vBox.lookup("#notRegisterGoTF");
        String notRegisterGoTFStr = notRegisterGoTF.getText().trim();
        editRegisterInfoVo.setNotRegisterGo(notRegisterGoTFStr);

        ComboBox vacateCB = (ComboBox) this.vBox.lookup("#vacateCB");
        if (vacateCB.getValue() != null) {
            int leave = -1;
            String vacateCBValue = (String) vacateCB.getValue();
            switch (vacateCBValue) {
                case "是":
                    leave = BOConstant.REGISTER_INFO_DELETED_NO;
                    break;
                case "否":
                    leave = BOConstant.REGISTER_INFO_DELETED_YES;
                    break;
            }
            editRegisterInfoVo.setIsVacate(leave);
        }

        TextField schoolYearTF = (TextField) this.vBox.lookup("#schoolYearTF");
        String schoolYearTFStr = schoolYearTF.getText().trim();
        editRegisterInfoVo.setSchoolYear(schoolYearTFStr);

        TextField semesterTF = (TextField) this.vBox.lookup("#semesterTF");
        String semesterTFStr = semesterTF.getText().trim();
        editRegisterInfoVo.setSemester(semesterTFStr);

        TextField classTF = (TextField) this.vBox.lookup("#classTF");
        String classTFStr = classTF.getText().trim();
        editRegisterInfoVo.setClassroom(classTFStr);


        return editRegisterInfoVo;
    }

}
